package com.howard.core;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.danga.MemCached.MemCachedClient;
import com.howard.action.LoginController;
import com.howard.core.cache.MemCachedFactory;
import com.howard.entity.User;
/**
 * session 失效过滤器
 * @author <a href="mailto:howard.he0329@gmail.com">Howard He</a>
 *
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(SessionInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if(logger.isDebugEnabled()) {
			logger.debug("Interceptor Name:" + this.getClass().getSimpleName());
		}
		if(handler instanceof LoginController) {
			return true;
		}
		Cookie[] cookies = request.getCookies();
		String sid = null;
		User user = null;
		if(cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie c = cookies[i];
				sid = c.getValue();
			}
			sid = StringUtils.substringBefore(sid, ".");
			if(logger.isDebugEnabled())
				logger.debug("SessionId: " + sid);
			MemCachedClient client = MemCachedFactory.createMemCacheClient();
			if(client.keyExists(sid)) {
				user = (User)client.get(sid);
				if(logger.isDebugEnabled())
					logger.debug("user:" + user);
				client.replace(sid, client.get(sid), new Date(System.currentTimeMillis() + 30 * 1000));
			}
		}
		if(user != null) {
			return true;
		}
		response.sendRedirect(request.getContextPath() + "/jsp/login/login.jsp");
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//TODO
	}
}
